﻿using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Cmd;
using GameData;
using JetBrains.Annotations;
using JYLib;
using UnityEngine.UI;

public class NumPanel : MonoBehaviour
{

    public GameObject Btn;

    private int iRetUSB = 0;
    private int iRetCOM = 0;

    public Text CoText;
    public InputField InputField;

    public float readTime;
    public bool isInread;
    public bool isOnstart;
    public RecTipsPanel RecTipsPanel;

    public ReceiveUI ReceiveUi;
    public bool isNorDll = true;


    public void OnStartLoading()
    {
        if (!isOnstart&& isNorDll)
        {
            InvokeRepeating("OnInLoad", 1f, 2f);
            isOnstart = true;

        }

    }
    //
    public void OnStopLoading()
    {
        CancelInvoke("OnInLoad");
        isOnstart = false;

    }


    void OnInLoad()
    {
        if (!isInread&& isNorDll)
        {
            try
            {
                if ((iRetCOM == 1) || (iRetUSB == 1))
                {

                    int authenticate = CVRSDK.CVR_Authenticate();
                    if (authenticate == 1)
                    {
                        int readContent = CVRSDK.CVR_Read_Content(4);
                        //

                        //
                        if (readContent == 1)
                        {
                            isInread = true;
                            this.CoText.text = "读卡操作成功！";
                            //读取数据
                            FildData();

                        }
                        else
                        {
                            this.CoText.text = "读卡操作失败！";
                        }
                    }
                    else
                    {
                        this.CoText.text = "未放卡或卡片放置不正确";
                    }
                }
                else
                {
                    this.CoText.text = "初始化失败！";
                }
            }
            catch (Exception ex)
            {

            }
        }
    }


	// Use this for initialization
	void Start ()
	{
	    isNorDll = true;
        isOnstart = false;
        int iPort;
	    try
	    {
            for (iPort = 1001; iPort <= 1016; iPort++)
            {
                iRetUSB = CVRSDK.CVR_InitComm(iPort);
                if (iRetUSB == 1)
                {

                    break;
                }
            }
            //
            if (iRetUSB != 1)
            {
                for (iPort = 1; iPort <= 4; iPort++)
                {
                    iRetCOM = CVRSDK.CVR_InitComm(iPort);
                    if (iRetCOM == 1)
                    {
                        break;
                    }
                }
            }
            //
            if ((iRetCOM == 1) || (iRetUSB == 1))
            {
                CoText.text = "初始化成功！";
            }
            else
            {
                CoText.text = "初始化失败！";
            }
        }
	    catch (Exception)
	    {
	        isNorDll = false;
            throw;
	    }


	    readTime = 1000;
	    isInread = false;

        EventTriggerListener.Get(Btn).onClick = OnClickBtn;
	}
	
    //
    void OnClickBtn(GameObject obj)
    {
        //
        string str = InputField.text;

        if (!string.IsNullOrEmpty(str))
        {
            //
            CheckNum checkNum = new CheckNum();
            //判断身份证或者收据
            //只需要输入身份证后面6位
            //或者单据

            //判断身份证
            int len = str.Length;
            Debug.Log("长度为："+len);
            if ( len==6 || len == 18)//长度为6
            {
                Debug.Log("身份证后：" + len);
                //
                checkNum.idCard = str;
            }
            else
            {
                Debug.Log("单据：：" + len);

                //
                checkNum.payNum = str;

            }

            GetRecNumToNUm GetRecNumToNUm = new GetRecNumToNUm();
            GetRecNumToNUm.Send(checkNum, OnCheckNum);
        }

        // isInread = false;

    }


    //
    /// <summary>
    /// 验证18位身份证号
    /// </summary>
    /// <param name="Id">身份证号</param>
    /// <returns>验证成功为True，否则为False</returns>
    private static bool CheckIDCard18(string Id)
    {
        long n = 0;
        if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false)
        {
            return false;//数字验证
        }
        string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
        if (address.IndexOf(Id.Remove(2)) == -1)
        {
            return false;//省份验证
        }
        string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
        DateTime time = new DateTime();
        if (DateTime.TryParse(birth, out time) == false)
        {
            return false;//生日验证
        }
        string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
        string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
        char[] Ai = Id.Remove(17).ToCharArray();
        int sum = 0;
        for (int i = 0; i < 17; i++)
        {
            sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
        }
        int y = -1;
        Math.DivRem(sum, 11, out y);
        if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
        {
            return false;//校验码验证
        }
        return true;//符合GB11643-1999标准
    }

    public Text lblAddress;
    public Text lblSex;
    public Text lblIdCard;
    public Text lblName;
    public Text lblNation;
    public Text lblDay;


    public void FildData()
    {
        Debug.Log("读取数据");
        //
        string url=Application.dataPath + "/Plugins/wz.txt";
        if (File.Exists(url))
        {
            Debug.Log("存在文件"+ Encoding.Default);

            Gb2312Encoding GB2312 = new Gb2312Encoding();

            using (var sr = new StreamReader(url, GB2312))

            {

                Debug.Log("读取：");
                string strLine = sr.ReadLine();
                Debug.Log("名字:" + strLine);
                lblName.text = strLine;

                strLine = sr.ReadLine();
                Debug.Log("性别:" + strLine);
                lblSex.text = strLine;

                strLine = sr.ReadLine();
                Debug.Log("种族:" + strLine);
                //lblSex.text = strLine;

                strLine = sr.ReadLine();
                Debug.Log("出生:" + strLine);
                lblDay.text = strLine;

                strLine = sr.ReadLine();
                Debug.Log("地址:" + strLine);
                lblAddress.text = strLine;

                strLine = sr.ReadLine();
                Debug.Log("身份证号:" + strLine);
                lblIdCard.text = strLine;



                strLine = sr.ReadLine();
                Debug.Log("公安局:" + strLine);
                lblNation.text = strLine;
                sr.Close();

                //发送取号
                //弹出对话框
                Debug.Log("=====身份证号码:"+ lblIdCard.text);
                //
                CheckNum checkNum = new CheckNum();
                checkNum.idCard = lblIdCard.text;
                checkNum.name = lblName.text;
                GetRecNumToNUm GetRecNumToNUm = new GetRecNumToNUm();
                GetRecNumToNUm.Send(checkNum, OnCheckNum);

            }

        }
            //读取外部文件

       
    }

    private List<NumberInfo> numListInfo; 

    public void OnCheckNum(AllNumbers allNumbers)
    {
        
        if (allNumbers.NumberInfoList.Count<=0 && allNumbers.OtherList.Count<=0)
        {
            RecTipsPanel.OnShowRec(OnReStart, "没有该客户信息,请使用认筹客户身份证");
        }
        else
        {
            numListInfo = allNumbers.NumberInfoList;
            numListInfo.AddRange(allNumbers.OtherList);
            string strk = "";
            for (int i = 0; i < numListInfo.Count; i++)
            {
                NumberInfo numberInfo = allNumbers.NumberInfoList[i];
                strk += (numberInfo.value);
                if (i!=numListInfo.Count-1)
                {
                    strk += ",";
                }
            }
            //
            RecTipsPanel.OnShowRec(OnReStart, strk);
        }
    }



    void OnReStart()
    {

        if (numListInfo!=null && numListInfo.Count>0)
        {
            //打印票据
            ReceiveUi.StartPrint(OnResp, numListInfo);
        }
        else
        {
            OnResp();
        }

        isInread = false;
    }

    void OnResp()
    {
        isInread = false;
        numListInfo.Clear();
    }

	// Update is called once per frame
	void Update () {
	
	}
}
